package ai.peanut.one.api.tread.testLock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProduAndConsumeLock {

    private final int max ;
    private final  int min  ;
    private volatile AtomicInteger index ;
    private Lock lock ;
    private Condition proCon ;
    private Condition cusCon ;

    public ProduAndConsumeLock(){
        this.max = 20 ;
        this.min = 10 ;
        index = new AtomicInteger(11) ;
        this.lock = new ReentrantLock() ;
        this.cusCon = lock.newCondition() ;
        this.proCon = lock.newCondition() ;
    }


    public  void pro(){
        try{
            lock.lock();

            if( index.intValue() >= max ){
                System.out.println("生产达到峰值");
                proCon.await();
            }

            int a = index.incrementAndGet() ;
            System.out.println("开始生产:" + a ) ;
            cusCon.signalAll();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public  void csu(){
        try{
            lock.lock();

            if( index.intValue() <= min ){
                System.out.println("消费到底啦。。。");
                cusCon.await();
            }

            int a = index.decrementAndGet() ;
            System.out.println("开始消费:" + a ) ;
            proCon.signalAll();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
